package com.langfeiyes.pattern.composite.v2;



import java.util.ArrayList;
import java.util.List;

/**
 * 组合菜单，包含其他叶子菜单/子组合菜单
 * 只实现Composite 方法
 */
public class MenuComposite extends Component {

    private int level;
    private String name;
    private List<Component> children = new ArrayList<>();
    public MenuComposite(String name, int level) {
        this.name = name;
        this.level = level;
    }

    @Override
    public void print() {
        System.out.println("Composite：" + name);
        for (Component child : children) {
            for (int i = 0; i < this.level; i++) {
                System.out.print("--");
            }
            child.print();
        }
    }
    @Override
    public boolean isLeaf() {
        return false;
    }
    //需要重写组合菜单自己方法
    @Override
    public void addChild(Component child) {
       if(child != null){
           children.add(child);
       }
    }

    @Override
    public void removeChild(Component child) {
        if(child != null){
            children.remove(child);
        }
    }

    @Override
    public Component getChild(int index) {

        if(index >= 0 && index < children.size()){
            return  children.get(index);
        }
        return null;
    }
}
